package com.xinxin.intelligenceexam.studyMenu.sovleSlide;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.xinxin.intelligenceexam.R;

import java.util.ArrayList;
import java.util.List;

public class SlideActivity extends AppCompatActivity {

    /**
     * viewpager横向滑动的阈值
     */
    private static final int THRESHOLD_X_VIEW_PAGER = 60;
    /**
     * listview竖向滑动的阈值
     */
    private static final int THRESHOLD_Y_LIST_VIEW = 20;

    /**
     * 下拉刷新控件
     */
    private SwipeRefreshLayout mRefreshLayout;
    private BottomScrollView mScrollView;
    private ViewPager mViewPager;
    private ListView mListView;
    private TextView mTextView;

    private ViewPagerAdapter mViewPagerAdapter;
    private ListViewAdapter mListViewAdapter;

    private boolean isSvToBottom = false;

    private float mLastX;
    private float mLastY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_slide);
        initView();
        initAction();
        fixSlideConflict();
    }

    private void fixSlideConflict() {
        //模拟在上面点击不能操作scrollView
        mTextView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_UP){
                    //允许ScrollView截断点击事件，ScrollView可滑动
                    mScrollView.requestDisallowInterceptTouchEvent(false);
                }else{
                    //不允许ScrollView截断点击事件，点击事件由子View处理
                    mScrollView.requestDisallowInterceptTouchEvent(true);
                }
                return true;
            }
        });
        // ViewPager滑动冲突解决
        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        mLastX = motionEvent.getX();//手指的X坐标
                        break;
                    case MotionEvent.ACTION_MOVE:
                        //超过预知，进制SwipeRefreshLayout下拉刷新，进制ScrollView截断点击事件
                        if(Math.abs(motionEvent.getX()-mLastX)>THRESHOLD_X_VIEW_PAGER){
                            mRefreshLayout.setEnabled(false);
                            mScrollView.requestDisallowInterceptTouchEvent(true);
                        }
                        break;
                    //手指抬起，恢复状态
                    case MotionEvent.ACTION_UP:
                        mRefreshLayout.setEnabled(true);
                        mScrollView.requestDisallowInterceptTouchEvent(false);
                        break;
                }
                //返回true，则表示监听器处理了该事件，这里返回false，会继续传递事件
                return false;
            }
        });

        // ListView滑动冲突解决
        mListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();

                if(action == MotionEvent.ACTION_DOWN) {
                    mLastY = event.getY();
                }
                if(action == MotionEvent.ACTION_MOVE) {
                    int top = mListView.getChildAt(0).getTop();//相对于父布局的位置
                    float nowY = event.getY();
                    //ScrollView在未滑动到底部时候，如果点击并滑动ListView时候，ListView是不能滑动的，不禁止
                    if(!isSvToBottom) {
                        // 允许scrollview拦截点击事件, scrollView滑动
                        mScrollView.requestDisallowInterceptTouchEvent(false);
                        //如果ScrollView滑动到底部，且ListView已经到顶部，继续下拉ListView，其实会拉动ScrollView，不禁止
                    } else if(top == 0 && nowY - mLastY > THRESHOLD_Y_LIST_VIEW) {
                        // 允许scrollview拦截点击事件, scrollView滑动
                        mScrollView.requestDisallowInterceptTouchEvent(false);
                    } else {
                        // 不允许scrollview拦截点击事件， listView滑动
                        mScrollView.requestDisallowInterceptTouchEvent(true);
                    }
                }
                return false;
            }
        });
    }


    private void initAction() {
        //模拟下拉刷新，0.5秒后，下拉刷新状态视图消失
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mRefreshLayout.setRefreshing(false);
                    }
                }, 500);
            }
        });

        mScrollView.setScrollToBottomListener(new BottomScrollView.OnScrollToBottomListener() {
            @Override
            public void onScrollToBottom() {
                isSvToBottom = true;
            }

            @Override
            public void onNotScrollToBottom() {
                isSvToBottom = false;
            }
        });
    }

    private void initView() {
        mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.main_refresh_layout);
        mScrollView = (BottomScrollView) findViewById(R.id.main_scroll_view);
        mViewPager = (ViewPager) findViewById(R.id.main_viewpager);
        mListView = (ListView) findViewById(R.id.main_list_view);
        mTextView = (TextView) findViewById(R.id.tv_map);

        mListViewAdapter = new ListViewAdapter(this, getListViewData());
        mListView.setAdapter(mListViewAdapter);

        mViewPagerAdapter = new ViewPagerAdapter(this, getViewPagerData());
        mViewPager.setAdapter(mViewPagerAdapter);

    }

    private List<String> getListViewData() {
        List<String> data = new ArrayList<>();
        for(int i = 1; i <= 20; i ++) {
            data.add(i + " item");
        }

        return data;
    }

    private List<String> getViewPagerData() {
        List<String> data = new ArrayList<>();
        for(int i = 1; i <= 5; i ++) {
            data.add("page " + i);
        }

        return data;
    }

    class ViewPagerAdapter extends PagerAdapter {

        private Context mContext;
        private List<String> mData;

        public ViewPagerAdapter(Context context, List<String> data) {
            this.mContext = context;
            this.mData = data;
        }

        @Override
        public int getCount() {
            return mData == null ? 0 : mData.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.view_viewpager_item, container, false);
            ((TextView)view.findViewById(R.id.viewpager_item_tv)).setText(this.mData.get(position));
            container.addView(view);
            return view;
        }
    }
    class ListViewAdapter extends BaseAdapter {

        private Context mContext;
        private List<String> mData;

        public ListViewAdapter(Context context, List<String> data) {
            this.mContext = context;
            this.mData = data;
        }

        @Override
        public int getCount() {
            return this.mData == null ? 0 : this.mData.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if(convertView == null) {
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.view_list_item, parent, false);
                viewHolder.tv = (TextView) convertView.findViewById(R.id.list_item_tv);

                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.bindData(mData.get(position));
            return convertView;
        }

        private class ViewHolder {
            public TextView tv;

            public void bindData(String str) {
                tv.setText(str);
            }
        }
    }
}
